//
//  TribeViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/4.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "TribeViewController.h"
#import "CommendTribeCell.h"
#import "MyCreateTribeListCell.h"
#import "MyJointribeListCell.h"
#import "RQQZCell.h"
#import "TribeModel.h"
#import "ContentListCell.h"
#import "TitleCell.h"
#import "TitleView.h"
#import "ContentListModel.h"
#import "SearchViewController.h"
#import "CreateTribeViewController.h"
#import "TribeDetailViewController.h"
#import "MsgCenterViewController.h"
#import "MyAddTribeListViewController.h"
#import "ArticleWebViewController.h"
#import "TopicleWebViewController.h"

#import "DFLineCellManager.h"
#import "DFBaseLineCell.h"
#import "DFLineLikeItem.h"
#import "DFLineCommentItem.h"
#import "CommentInputView.h"

#import "MMPopupItem.h"
#import "MMSheetView.h"
#import "MMPopupWindow.h"
#import "DFLikeCommentView.h"
#import "YXCustomActionSheet.h"
#import "DyShare.h"

#import "DFImagePreviewViewController.h"

#import "IndexModel.h"
#define CommendTribe (@"CommendTribeCell")
#define MyCreateTribeList (@"MyCreateTribeListCell")
#define MyJointribeList (@"MyJointribeListCell")
#define RQQZ (@"RQQZCell")
#define ContentList (@"ContentListCell")
#define Title (@"TitleCell")
#define sectionHeaderHeight (15)
#define Arc4randomColor [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];

@interface TribeViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,MyCreateTribeDelegate,MyJointribeDelegate,CommendTribeDelegate,DFLineCellDelegate, CommentInputViewDelegate,UINavigationControllerDelegate, DFImagePreviewViewControllerDelegate, YXCustomActionSheetDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (strong, nonatomic) TitleView *titleView;
@property (nonatomic,strong)NSMutableDictionary *dataSource;

@property (strong, nonatomic) UIButton *noticebtn;
@property (strong, nonatomic) UILabel *noticecount;

@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;


@property (strong, nonatomic) CommentInputView *commentInputView;


@property (strong, nonatomic) NSString * currentItemId;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (strong, nonatomic) NSMutableArray *topicHeights;

@end

@implementation TribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageToEnd = NO;
    self.page = 1;
    [self setupNav];
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadNetworkData];
     [self createUI];
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"joinTribeNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(joinTribeNotification) name:@"joinTribeNotification" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadNetworkData) name:@"CreateMyTribe" object:nil];
   
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(joinTribeNotification) name:@"GuanZhuRQQZ" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    [self getMsgCount];
    [_commentInputView addNotify];
    
    [_commentInputView addObserver];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_commentInputView removeNotify];
    
    [_commentInputView removeObserver];
}
- (void)joinTribeNotification{
    [self loadNetworkData];
}
- (void)clickNotice:(id)sender {
    MsgCenterViewController *vc = [[MsgCenterViewController alloc] initWithNibName:@"MsgCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getMsgCount {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/sys/index/message/count", APIYIGOU];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSInteger count = [[dict objectForKey:@"data"] integerValue];
        self.noticecount.text = [NSString stringWithFormat:@"%ld", count];
        if (count == 0) {
            self.noticecount.hidden = YES;
        } else {
            self.noticecount.hidden = NO;
        }
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

#pragma -mark 设置导航栏
- (void)setupNav{
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"部落"];
    
    self.titleView = [[TitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 55, 44)];
    self.titleView.backgroundColor = [UIColor clearColor];
    UISearchBar *searchbar = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 7, ScreenWidth - 65, 30)];
    searchbar.searchBarStyle = UISearchBarStyleDefault;
    searchbar.placeholder = @"搜索你喜欢的部落";
    searchbar.layer.masksToBounds = YES;
    searchbar.layer.cornerRadius = 4.f;
    searchbar.delegate = self;
    [self.titleView addSubview:searchbar];
    
    self.noticebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.noticebtn.frame = CGRectMake(ScreenWidth - 40, 12, 20, 20);
    [self.noticebtn setBackgroundImage:[UIImage imageNamed:@"topnotice.png"] forState:UIControlStateNormal];
    [self.noticebtn addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *clickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clickbtn.frame = CGRectMake(ScreenWidth - 50, 0, 40, 44);
    [self.titleView addSubview:clickbtn];
    [clickbtn addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
    
    self.noticecount = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 10, 10)];
    self.noticecount.font = [FontTool fontWithSize:10];
    self.noticecount.textAlignment = NSTextAlignmentCenter;
    self.noticecount.textColor = [UIColor whiteColor];
    self.noticecount.backgroundColor = [UIColor colorWithHexString:@"0EA1B6"];
    self.noticecount.layer.masksToBounds = YES;
    self.noticecount.layer.cornerRadius = 5.f;
    self.noticecount.text = @"1";
    self.noticecount.userInteractionEnabled = NO;
    self.noticecount.hidden = YES;
    [self.noticebtn addSubview:self.noticecount];
    [self.titleView addSubview:self.noticebtn];

    self.navigationItem.titleView = self.titleView;
}

- (void)createUI{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone ;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self addRefreshHeader:self.tableView];
    [self addLoadMoreFooter:self.tableView];
    _items = [NSMutableArray array];
    
    _itemDic = [NSMutableDictionary dictionary];
    
    _commentDic = [NSMutableDictionary dictionary];
    
    [self initCommentInputView];

}

#pragma -mark TableView DataSource & Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    if (indexPath.section == 0) {
        return 155;
    }else if (indexPath.section == 1){
        return 160;
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            return 60;
        }else if (indexPath.row == model.commendTribe.count+1){
            return 15;
        }
        return 150;
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            return 60;
        }
        return 145;
    }else{
        TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
        NSInteger number = indexPath.section - 4;
         NSLog(@"indexPath:%ld",(long)indexPath.section);
        NSArray *array = [NSArray new];
        array = model.dynamicList;
         NSDictionary *dic = [array objectAtIndex:number];
        
        if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"01"]) {
            return 440;
        
        }else{
//            NSLog(@"indexPath:%ld",(long)indexPath.section);
//            DFBaseLineItem *item = [_items objectAtIndex:indexPath.section - 4];
//            DFBaseLineCell *typeCell = [self getCell:[item class]];
//            return [typeCell getReuseableCellHeight:item]+40;
            NSNumber *height = self.topicHeights[indexPath.section - 4];
            return [height integerValue];
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    if (indexPath.section == 0) {
        MyCreateTribeListCell *cell = GET_CELL(MyCreateTribeListCell, MyCreateTribeList);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell contentWithArray:model.myCreateTribeList];
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section == 1){
        MyJointribeListCell *cell = GET_CELL(MyJointribeListCell, MyJointribeList);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell contentWithArray:model.myJointribeList title:@"我加入的部落"];
        cell.delegate = self;
        return cell;
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            TitleCell *cell = GET_CELL(TitleCell, Title);
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.titleLabel.text = @"精选部落";
            
            return cell;
        }else if (indexPath.row == model.commendTribe.count+1){
            UITableViewCell *cell = [[UITableViewCell alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 15)];
            cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
            return cell;
        }
        CommendTribeCell *cell = GET_CELL(CommendTribeCell, CommendTribe);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSLog(@"index:%ld",indexPath.row - 1);
        NSDictionary *dic = [model.commendTribe objectAtIndex:indexPath.row-1];
        cell.model = [[CommendTribeModel alloc]initWithDictionary:dic error:nil];
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section == 3){
        
        if (indexPath.row == 0) {
            TitleCell *cell = GET_CELL(TitleCell, Title);
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.titleLabel.text = @"人气酋长";
            return cell;
        }else if (indexPath.row == model.rqqz.count +1){
            UITableViewCell *cell = [[UITableViewCell alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 15)];
            cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
            return cell;
        }
        RQQZCell *cell = GET_CELL(RQQZCell, RQQZ);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDictionary *dic = [model.rqqz objectAtIndex:indexPath.row-1];
        cell.model = [[RQQZModel alloc]initWithDictionary:dic error:nil];
        
        return cell;
    }else{
        
        NSInteger number = indexPath.section - 4;
       
        NSArray *array = [NSArray new];
        array = model.dynamicList;
//        NSInteger count = array.count;
        NSDictionary *dic = [array objectAtIndex:number];
        if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"01"]) {
            ContentListCell *cell = GET_CELL(ContentListCell,@"ContentListCell");
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            [cell contentWithDic:[dic objectForKey:@"content"]];
             return cell;
        }else if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"00"]){
            DFBaseLineItem *item = [_items objectAtIndex:number];
            DFBaseLineCell *typeCell = [self getCell:[item class]];
            NSString *reuseIdentifier = NSStringFromClass([typeCell class]);
            DFBaseLineCell *cell = [tableView dequeueReusableCellWithIdentifier: reuseIdentifier];
            if (cell == nil ) {
                cell = [[[typeCell class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            }else{
                NSLog(@"重用Cell: %@", reuseIdentifier);
            }
            
            cell.delegate = self;
            
            cell.separatorInset = UIEdgeInsetsZero;
            if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                cell.layoutMargins = UIEdgeInsetsZero;
            }
            [cell updateWithItem:item];
            
            return cell;
        }
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    
    return model.dynamicList.count+4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 1;
            break;
        case 2:
            return model.commendTribe.count+2;
            break;
        case 3:
            return model.rqqz.count+1;
            break;
        default:
            break;
    }
    return 1;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    if (indexPath.section ==0||indexPath.section == 1) {
        
        return;

    }else if (indexPath.section ==2){
        
        if (indexPath.row == 0) {
            return;
        }
        NSDictionary *dic = [model.commendTribe objectAtIndex:indexPath.row-1];
        NSString *tribeID = [dic objectForKey:@"tribe_id"];
        TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
        detail.tribeID = tribeID;
        [self.navigationController pushViewController:detail animated:YES];
    }else if (indexPath.section ==3){
        if (indexPath.row == 0) {
            return;
        }
        NSDictionary *dic = [model.rqqz objectAtIndex:indexPath.row-1];
        NSString *userID = [dic objectForKey:@"user_id"];
        [[GoToManager sharedGoToManager] go:self type:ToHisCenter data:userID];
        
    }
    else{
       
        NSDictionary *dicArticle = [model.dynamicList objectAtIndex:indexPath.section -4];
        NSDictionary *detailTopicle = [dicArticle objectForKey:@"content"];
        if ([[detailTopicle objectForKey:@"content_type"]isEqualToString:@"00"]) {
            [[GoToManager sharedGoToManager] go:self type:ToArticleDetail data:detailTopicle];
        }
        
    }
}

- (void)calculateHeight {
    TribeModel *model = [[TribeModel alloc]initWithDictionary:self.dataSource error:nil];
    //NSInteger number = indexPath.section - 4;
    [self.topicHeights removeAllObjects];
    NSArray *array = [NSArray new];
    array = model.dynamicList;
    //        NSInteger count = array.count;
    for(NSInteger i = 0; i < _items.count; i++) {
        NSDictionary *dic = [array objectAtIndex:i];
        if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"01"]) {
            NSInteger height = 10;
            [self.topicHeights addObject:[NSNumber numberWithInteger:height]];
        } else {
            DFBaseLineItem *item = [_items objectAtIndex:i];
            DFBaseLineCell *typeCell = [self getCell:[item class]];
            NSInteger height = [typeCell getReuseableCellHeight:item]+40;
            [self.topicHeights addObject:[NSNumber numberWithInteger:height]];
        }
    }
}

- (void)loadNetworkData {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/hytribe/tribeInit", APIYIGOU];
    self.page = 1;
    [self.dataSource removeAllObjects];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *data = [dict objectForKey:@"data"];
        [self.dataSource removeAllObjects];
        self.dataSource = [NSMutableDictionary dictionaryWithDictionary:data];

        [_items removeAllObjects];
        [self initDataWithArray: [self.dataSource objectForKey:@"dynamicList"]];
        [self calculateHeight];
        __weak __typeof(self) weakself= self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.tableView reloadData];
            [weakself.tableView.header endRefreshing];
        });
    } error:^(YTKBaseRequest *request) {
         [self.tableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
         [self.tableView.header endRefreshing];
    }];
}

#pragma mark 上拉、下拉
- (void)refresh {
    [super refresh];
    [self.dataSource removeAllObjects];
    [self loadNetworkData];
}

- (void)loadMore {
    [super loadMore];
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = nil;
    long limit = 5;
    self.page+=1;
    url = [NSString stringWithFormat:@"%@/hytribe/getIndexMoreContent?page=%ld&limit=%ld", APIYIGOU, self.page,limit];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic = [dict objectForKey:@"data"];
        NSArray *addTopicListArr = [dataDic objectForKey:@"list"];
        if (addTopicListArr.count == 0) {
            [ViewFactory showSuccess:@"没有更多数据了！"];
            [self.tableView.footer endRefreshing];
            return ;
        }
        NSArray *oldTopicListArr = [self.dataSource objectForKey:@"dynamicList"];
        NSMutableArray *newTopicListArr = [NSMutableArray arrayWithArray:oldTopicListArr];
        [newTopicListArr addObjectsFromArray:addTopicListArr];
        [self.dataSource removeObjectForKey:@"dynamicList"];
        [self.dataSource setObject:newTopicListArr forKey:@"dynamicList"];
        
        [self.dataSource removeObjectForKey:@"dynamicList"];
        [self.dataSource setObject:newTopicListArr forKey:@"dynamicList"];
        
        [self initDataWithArray:addTopicListArr];
       
        [self calculateHeight];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            
        });
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
#pragma -mark 搜索
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchViewController *vc = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}

#pragma mark -MyJointribeDelegate

-(void)didClickMyJointribeWithTbibeID:(NSString *)tribeID
{
    //点击更多
    if ([tribeID isEqualToString:@"0"]) {
        MyAddTribeListViewController *vc = [[MyAddTribeListViewController alloc] initWithNibName:@"MyAddTribeListViewController" bundle:nil];
        vc.type = IMyAddTribeListShow;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
    [self.navigationController pushViewController:detail animated:YES];
    detail.tribeID = tribeID;
}

#pragma mark- 精选部落
-(void)didClickCommendTribeWithTbibeID:(NSString *)tribeID{
    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
    [self.navigationController pushViewController:detail animated:YES];
    detail.tribeID = tribeID;
}
#pragma mark -我创建的部落详情和新建部落
-(void)didClickImgWithTbibeID:(NSString *)tribeID{
    //0表示创建部落
    if ([tribeID isEqualToString:@"0"]) {
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TribeStoryBoard" bundle:[NSBundle mainBundle]];
        CreateTribeViewController *createVC = [storyboard instantiateViewControllerWithIdentifier:@"CreateTribeViewController"];
        [self.navigationController pushViewController:createVC animated:YES];
        createVC.tribeID = tribeID;
    }else{
        TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
        [self.navigationController pushViewController:detail animated:YES];
        detail.tribeID = tribeID;
    }
}


#pragma 文章相关方法
- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

//初始化文章数据
-(void) initDataWithArray:(NSArray *)array
{
    
    NSArray *topicArr = array;
    for (NSDictionary *tmpDic in topicArr) {
        NSDictionary *topicDic = [tmpDic objectForKey:@"content"];
        NSLog(@"dic:%@",topicDic);
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.user_id = [topicDic objectForKey:@"user_id"];
        textImageItem.head_url = [[topicDic objectForKey:@"hyUser"] objectForKey:@"head_url"];
        textImageItem.nick_name = [[topicDic objectForKey:@"hyUser"] objectForKey:@"nick_name"];
        textImageItem.title = [topicDic objectForKey:@"title"];
        textImageItem.content_desc = [topicDic objectForKey:@"content_desc"];
        textImageItem.tribe_name = [topicDic objectForKey:@"tribe_name"];
        textImageItem.publish_tm = [topicDic objectForKey:@"publish_tm"];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.tribe_id = [topicDic objectForKey:@"tribe_id"];
        textImageItem.shareUrl = [topicDic objectForKey:@"shareUrl"];
        textImageItem.cover_img = [topicDic objectForKey:@"cover_img"];
        NSArray *picArr = [topicDic objectForKey:@"mediaList"];
        NSMutableArray *srcImages = [NSMutableArray array];
        for (NSDictionary *tmpDic in picArr) {
            NSString *imgString =  [tmpDic objectForKey:@"media_url"];
            [srcImages addObject:imgString];
        }
        [textImageItem.srcImages removeAllObjects];
        
        textImageItem.srcImages = srcImages;
        
        NSArray *contentCmt = [tmpDic objectForKey:@"contentCmtList"];
        
        for (NSDictionary *cmtDic in contentCmt) {
            NSLog(@"cmtArr:%@",cmtDic);
            DFLineCommentItem *commentItem1_1 = [[DFLineCommentItem alloc] init];
            commentItem1_1.commentId = [cmtDic objectForKey:@"comment_id"];
            commentItem1_1.userId = [cmtDic objectForKey:@"user_id"];
            commentItem1_1.userNick = [cmtDic objectForKey:@"user_nike_name"];
            if (![[cmtDic objectForKey:@"reply_user_id"]isEqualToString:@""]) {
                commentItem1_1.replyUserId = [cmtDic objectForKey:@"reply_user_id"];
                commentItem1_1.replyUserNick = [cmtDic objectForKey:@"reply_user_nike_name"];
            }
            
            commentItem1_1.text = [cmtDic objectForKey:@"comment"];
            
            [textImageItem.comments addObject:commentItem1_1];
        }
        
        NSArray *contentLike = [tmpDic objectForKey:@"contentLikeList"];
        [textImageItem.likes removeAllObjects];
        for (NSDictionary *tmpDic in contentLike) {
            DFLineLikeItem *likeItem1_1 = [[DFLineLikeItem alloc] init];
            likeItem1_1.userId = [tmpDic objectForKey:@"user_id"];
            likeItem1_1.userNick = [tmpDic objectForKey:@"nick_name"];
            likeItem1_1.head_url = [tmpDic objectForKey:@"head_url"];
            [textImageItem.likes addObject:likeItem1_1];
        }
        [self addItem:textImageItem];
    }
    
}

#pragma mark - Method

-(DFBaseLineCell *) getCell:(Class)itemClass
{
    DFLineCellManager *manager = [DFLineCellManager sharedInstance];
    return [manager getCell:itemClass];
}

-(void)addItem:(DFBaseLineItem *)item
{
    [self insertItem:item index:_items.count];
}

-(void) addItemTop:(DFBaseLineItem *) item
{
    [self insertItem:item index:0];
}

-(void) insertItem:(DFBaseLineItem *) item index:(NSUInteger)index
{
    [self genCommentAttrString:item];
    
    [_items insertObject:item atIndex:index];
    
    [_itemDic setObject:item forKey:item.content_id];
    
//    [self.tableView reloadData];
}

-(DFBaseLineItem *) getItem:(NSString *) itemId
{
    return [_itemDic objectForKey:itemId];
    
}

-(void)addCommentItem:(DFLineCommentItem *)commentItem itemId:(NSString *)itemId replyCommentId:(NSString *)replyCommentId

{
    DFBaseLineItem *item = [self getItem:itemId];
    NSMutableArray *tmpArr = [NSMutableArray new];
    [tmpArr addObject:commentItem];
    [tmpArr addObjectsFromArray:item.comments];
    [item.comments removeAllObjects];
    item.comments = tmpArr;
    [self AddCommentDataRequestWithReplyCommentId:replyCommentId ContentId:itemId CommentText:commentItem.text];
    if (![replyCommentId isEqualToString:@"0"]) {
        DFLineCommentItem *replyCommentItem = [self getCommentItem:replyCommentId];
        
        commentItem.replyUserId = replyCommentItem.userId;
        commentItem.replyUserNick = replyCommentItem.userNick;
        
    }
    
    item.cellHeight = 0;
    [self genCommentAttrString:item];
    [self.tableView reloadData];
    
}

-(void) genCommentAttrString:(DFBaseLineItem *)item
{
    NSMutableArray *comments = item.comments;
    
    [item.commentStrArray removeAllObjects];
    
    for (int i=0; i<comments.count;i++) {
        DFLineCommentItem *comment = [comments objectAtIndex:i];
        [_commentDic setObject:comment forKey:comment.commentId];
        
        NSString *resultStr;
        if (comment.replyUserId == 0) {
            resultStr = [NSString stringWithFormat:@"%@: %@",comment.userNick, comment.text];
        }else{
            resultStr = [NSString stringWithFormat:@"%@回复%@: %@",comment.userNick, comment.replyUserNick, comment.text];
        }
        
        NSMutableAttributedString *commentStr = [[NSMutableAttributedString alloc]initWithString:resultStr];
        if (comment.replyUserId == 0) {
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(0, comment.userNick.length)];
        }else{
            NSUInteger localPos = 0;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(localPos, comment.userNick.length)];
            localPos += comment.userNick.length + 2;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.replyUserId] range:NSMakeRange(localPos, comment.replyUserNick.length)];
        }
        
        NSLog(@"ffff: %@", resultStr);
        
        [item.commentStrArray addObject:commentStr];
    }
}
-(void)onLike:(NSString *)contentId likeItem:(DFLineLikeItem *)likeItem type:(BOOL)type
{
    //点赞
    if (type) {
        
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        [tmpArr addObjectsFromArray:item.likes];
        [item.likes removeAllObjects];
        item.likes = tmpArr;
    }else {
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<item.likes.count; i++) {
            DFLineLikeItem *tmpItem =  [item.likes objectAtIndex:i];
            if ([tmpItem.userId isEqualToString:likeItem.userId]) {
                //                NSLog(@"有一样的");
                [array addObject:tmpItem];
            }
        }
        [item.likes removeObjectsInArray:array];
    }
    
    [self.tableView reloadData];
}

-(DFLineCommentItem *)getCommentItem:(NSString *)commentId
{
    return [_commentDic objectForKey:commentId];
}

-(void) initCommentInputView
{
    if (_commentInputView == nil) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _commentInputView.hidden = YES;
        _commentInputView.delegate = self;
        [self.view addSubview:_commentInputView];
    }
    
}
#pragma mark - DFLineCellDelegate


-(void)onComment:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.commentId = @"0";
    
    _commentInputView.hidden = NO;
    
    [_commentInputView show];
}
//-(void)onShare:(NSString *)itemId
//{
//    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
//    cusSheet.delegate = self;
//    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
//                              @{@"name":@"微信",@"icon":@"sns_wx"},
//                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
//                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
//                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},];
//    
//    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
//}


//- (void)onClickTitleLabel:(NSString *)tribeId
//{
//    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
//    [self.navigationController pushViewController:detail animated:YES];
//    detail.tribeID = tribeId;
//}

//点击左边头像 或者 点击评论和赞的用户昵称
//-(void)onClickUser:(NSString *)userId
//{
//    NSLog(@"userid:%@",userId);
//    UserViewController *controller = [[UserViewController alloc] init];
//    [self.navigationController pushViewController:controller animated:YES];
//    
//}
//-(void)onClickHeaderUserAvatar
//{
//    [self onClickUser:@"111"];
//}

-(void)onClickComment:(NSString *)commentId itemId:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.hidden = NO;
    
    _commentInputView.commentId = commentId;
    
    [_commentInputView show];
    
    DFLineCommentItem *comment = [_commentDic objectForKey:commentId];
    [_commentInputView setPlaceHolder:[NSString stringWithFormat:@"  回复: %@", comment.userNick]];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text
{
    [self onCommentCreate:commentId text:text itemId:_currentItemId];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text itemId:(NSString *) itemId
{
    
    DFLineCommentItem *commentItem = [[DFLineCommentItem alloc] init];
    commentItem.commentId = commentId;
    commentItem.userId = [UserData userid];
    commentItem.userNick = [UserData username];
    commentItem.text = text;
    [self addCommentItem:commentItem itemId:itemId replyCommentId:commentId];
}





#pragma mark - UIViewControllerPreviewingDelegate

-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:location];
    
    if(indexPath)
    {
        
        DFBaseLineCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        if (cell && [cell isKindOfClass:[DFTextImageLineCell class]]) {
            DFTextImageLineCell *imageCell = (DFTextImageLineCell *)cell;
            //            NSInteger index = [imageCell getIndexFromPoint:location];
            
            DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
            if (item && [item isKindOfClass:[DFTextImageLineItem class]]) {
                DFTextImageLineItem *textItem = (DFTextImageLineItem *) item;
                if (index == -1) {
                    return nil;
                }
                NSString *url  = [textItem.srcImages objectAtIndex:index];
                DFImagePreviewViewController *previewController=[[DFImagePreviewViewController alloc] initWithImageUrl:url itemId:item.content_id];
                previewController.delegate = self;
                previewController.preferredContentSize=CGSizeMake(300, 300);
                return previewController;
            }
        }
    }
    return nil;
}
-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
    [self showViewController:viewControllerToCommit sender:self];
}

ARRAY_INIT(topicHeights)

@end
